//
//  PersonalInfoEditController.m
//  囧途而行
//
//  Created by 杨璟 on 16/5/17.
//  Copyright © 2016年 YSKJ. All rights reserved.
//

#import "PersonalInfoEditController.h"
#import "EditingInfoCell.h"

#import "JTUser.h"
#import <SVProgressHUD.h>
#import <AVOSCloud.h>

@interface PersonalInfoEditController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) JTUser *editingUser;

@end

@implementation PersonalInfoEditController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.editingUser = [JTUser currentUser];
    self.navigationItem.title = @"资料修改";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(editComplete:)];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}

- (void)takePhotoFromPhone {
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
        
    }];
    
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
        
    }];
    
    UIAlertAction * action2 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:action];
    
    [alert addAction:action1];
    
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)editComplete:(UIBarButtonItem *)sender {
    [SVProgressHUD show];
    AVObject * obj = [AVObject objectWithoutDataWithClassName:@"_User" objectId:[JTUser currentUser].objectId];
    [obj setObject:self.editingUser.gender forKey:@"Gender"];
    [obj setObject:self.editingUser.nickname forKey:@"NickName"];
    
    if (self.editingUser.icon != nil) {
        AVFile *file = [AVFile fileWithData:self.editingUser.icon];
        [obj setObject:file forKey:@"HeadImage"];
        [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            }
        } progressBlock:^(NSInteger percentDone) {
            [SVProgressHUD showProgress:percentDone/100 status:@"正在上传头像"];
        }];
    }
    
    [obj saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [[AVUser currentUser] fetchInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                if (!error) {
                    JTUser *currentUser = [JTUser userWithCurrentUser:object];
                    [currentUser save];
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                }
            }];
        } else if (error) {
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }
    }];

}

#pragma mark - tableview delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EditingInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"onePersonalInfo"];
    
    cell.editingUser = self.editingUser;
    cell.row = indexPath.row;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
            [self takePhotoFromPhone];
            break;
        case 1: {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"输入新昵称" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                textField.placeholder = @"请输入新昵称";
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
            }];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:alert.textFields.firstObject];
                [tableView reloadData];
            }];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:alert.textFields.firstObject];
            }];
            
            [alert addAction:sure];
            [alert addAction:cancel];
            
            [self presentViewController:alert animated:YES completion:nil];
        }
            break;
        case 2: {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择性别" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *man = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                self.editingUser.gender = @"男";
                [tableView reloadData];
            }];
            UIAlertAction *woman = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                self.editingUser.gender = @"女";
                [tableView reloadData];
            }];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            [alert addAction:man];
            [alert addAction:woman];
            [alert addAction:cancel];
            
            [self presentViewController:alert animated:YES completion:nil];
        }
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

#pragma mark - imagepicker delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *oneImage = info[UIImagePickerControllerOriginalImage];
    self.editingUser.icon = UIImageJPEGRepresentation(oneImage, 0.3);
    [self.tableView reloadData];
}

//截取居中的方形图像
//- (UIImage *)cutPicture:(UIImage *)raw {
//    CGSize origImageSize = raw.size;CGRect newRect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH);float ratio = MAX(newRect.size.width / origImageSize.width, newRect.size.height / origImageSize.height);
//    //创建透明位图上下文
//    UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
//    //创建圆角矩形的对象，这里设置圆角为0
//    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect cornerRadius:0.0];
//    //裁剪图形上下文
//    [path addClip];
//    //让图片在缩略图绘制范围内居中
//    CGRect projectRect;projectRect.size.width = ratio * origImageSize.width;projectRect.size.height = ratio * origImageSize.height;projectRect.origin.x = (newRect.size.width - projectRect.size.width) / 2.0;projectRect.origin.y = (newRect.size.height - projectRect.size.height) / 2.0;
//    //在上下文中绘制图片
//    [raw drawInRect:projectRect];
//    //从上下文获取图片，并复制给item
//    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
//    //清理图形上下文
//    UIGraphicsEndImageContext();return smallImage;
//}

#pragma mark - KVO 
- (void)handleTextFieldTextDidChangeNotification:(NSNotification *)note {
    UITextField *tf = note.object;
    self.editingUser.nickname = tf.text;
    NSLog(@"%@", tf.text);
}

@end
